package com.protocolmeter.frame;

/**
 * @ClassName: BaseFrame
 * @Description: 英文帧结构
 * @author baozhijian
 * @date 2017年7月24日 下午4:30:33
 * @version V1.0
 */
public class Meterabroad implements Meter {

	private static String COMM_ANALYSIS_OK = "解析成功";
	private static String COMM_ANALYSIS_ERR_ID = "数据项ID不支持";
	private static String COMM_ANALYSIS_ERR_authority = "权限不足";
	private static String COMM_ANALYSIS_ERR_data = "数据非法（长度、值范围非法）";
	private static String COMM_ANALYSIS_ERR_TOKEN = "token解析失败";
	private static String COMM_ANALYSIS_ERR_OTHER = "其他错误";

	private String address;
	private String identification;
	private String len;
	private String data;
	private String Resultflag;

	private int type;

	public String getResultflag() {
		switch (Integer.valueOf(this.Resultflag)) {
		case 0:
			return COMM_ANALYSIS_OK;
		case 1:
			return COMM_ANALYSIS_ERR_ID;
		case 2:
			return COMM_ANALYSIS_ERR_authority;
		case 3:
			return COMM_ANALYSIS_ERR_data;
		case 4:
			return COMM_ANALYSIS_ERR_TOKEN;
		default:
			return COMM_ANALYSIS_ERR_OTHER;
		}
	}

	public Meterabroad(String address, String identification, String data) {
		this.address = address;
		this.identification = identification;
		this.data = data;

		this.len = Integer.toHexString(((this.identification + this.data).length() / 2) | 0x100).substring(1);

	}

	public Meterabroad(String sentdata, String frame) {
		switch (type) {
		case 1:
			readdecode(frame);
			break;
		case 2:
			writedecode(frame);
			break;
		default:
			break;
		}

	}

	private void writedecode(String frame) {
		this.address = frame.substring(0, 12);
		this.Resultflag = frame.substring(12, 14);
		this.len = frame.substring(14, 16);
		this.identification = frame.substring(16, 24);
		this.data = "";
	}

	private void readdecode(String frame) {
		this.address = frame.substring(0, 12);
		this.Resultflag = frame.substring(12, 14);
		this.len = frame.substring(14, 16);
		this.identification = frame.substring(16, 24);
		int len = Integer.valueOf(this.len, 16);
		this.data = frame.substring(24, 24 + (len - 4) * 2);
	}

	@Override
	public String toString() {
		if (this.data.equals("")) {
			return this.address + "02" + this.identification;
		} else {
			return this.address + "02" + this.len + this.identification + this.data;
		}
	}

	@Override
	public String Getdata() {
		// TODO Auto-generated method stub
		return null;
	}

}
